package com.letoken.platform.repo.admin.util;

import com.letoken.platform.repo.admin.res.system.QueryAdminMenuTreeRes;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


/**
 * 类名称：MenuTreeUtil
 * 类描述：递归构造树型结构
 *
 * @author Shirley
 */
public class MenuTreeUtil {

    /**
     * 创建树结构
     *
     * @param queryAdminMenuTreeResList
     * @return
     */
    public static List<QueryAdminMenuTreeRes> buildMenuTree(List<QueryAdminMenuTreeRes> queryAdminMenuTreeResList) {
        if (CollectionUtils.isEmpty(queryAdminMenuTreeResList)) {
            return null;
        }
        //返回的节点树
        List<QueryAdminMenuTreeRes> rootNodes = new ArrayList<>();
        Iterator<QueryAdminMenuTreeRes> it = queryAdminMenuTreeResList.iterator();
        while (it.hasNext()) {
            QueryAdminMenuTreeRes next = it.next();
            //parent（上级Id）为0的是根节点
            if ( Integer.valueOf(0).equals(next.getPid())) {
                rootNodes.add(next);
                it.remove();
            }
        }
        //遍历，找到二级节点
        for (QueryAdminMenuTreeRes regionTree : rootNodes) {
            List<QueryAdminMenuTreeRes> child = getChild(queryAdminMenuTreeResList, regionTree.getAdminMenuId());
            regionTree.setChildList(child);
        }
        return rootNodes;

    }

    /**
     * 查子节点
     *
     * @param regions
     * @param parentId
     * @return
     */
    public static List<QueryAdminMenuTreeRes> getChild(List<QueryAdminMenuTreeRes> regions, Integer parentId) {

        //子节点列表
        List<QueryAdminMenuTreeRes> childList = new ArrayList<>();
        Iterator<QueryAdminMenuTreeRes> it = regions.iterator();
        while (it.hasNext()) {
            QueryAdminMenuTreeRes regionTree = it.next();
            if (parentId.equals(regionTree.getPid())) {
                childList.add(regionTree);
                it.remove();
            }
        }

        //遍历 递归获取子节点的子节点
        for (QueryAdminMenuTreeRes regionTree : childList) {
            List<QueryAdminMenuTreeRes> child = getChild(regions, regionTree.getAdminMenuId());
            regionTree.setChildList(child);
        }
        //递归出口 childList长度为0
        if (childList.size() == 0) {
            return new ArrayList<>();
        }
        return childList;
    }
}
